package com.qys.livesMall.anchor.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qys.livesMall.anchor.constants.enums.AnchorSellTaskStatus;
import com.qys.livesMall.anchor.mapper.AnchorSellLivesApplyMapper;
import com.qys.livesMall.anchor.mapper.AnchorSellTaskMapper;
import com.qys.livesMall.anchor.model.dto.task.sys.SysSellLivesAnchorPageDTO;
import com.qys.livesMall.anchor.model.entity.AnchorLivesRoom;
import com.qys.livesMall.anchor.model.entity.AnchorLivesSession;
import com.qys.livesMall.anchor.model.entity.AnchorSellLivesApply;
import com.qys.livesMall.anchor.model.entity.AnchorSellTask;
import com.qys.livesMall.anchor.model.vo.task.app.child.SellLivesChild;
import com.qys.livesMall.anchor.model.vo.task.sys.SysSellLivesAnchorPageVO;
import com.qys.livesMall.anchor.service.AnchorLivesRoomService;
import com.qys.livesMall.anchor.service.AnchorLivesSessionService;
import com.qys.livesMall.anchor.service.AnchorSellLivesApplyService;
import com.qys.livesMall.app.user.model.entity.H2AppUser;
import com.qys.livesMall.common.enums.CommonPassFlag;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.shop.modal.entity.ShopGoodsInfo;
import com.qys.livesMall.shop.modal.entity.ShopSellTask;
import com.qys.livesMall.shop.service.ShopGoodsInfoService;
import com.qys.livesMall.shop.service.ShopSellTaskProductService;
import com.qys.livesMall.shop.service.ShopSellTaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 主播直播带货申请表 服务实现类
 * </p>
 *
 * @author wzy
 * @since 2023-06-20
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AnchorSellLivesApplyServiceImpl extends ServiceImpl<AnchorSellLivesApplyMapper, AnchorSellLivesApply> implements AnchorSellLivesApplyService {

    private final ShopSellTaskProductService taskProductService;
    private final ShopGoodsInfoService goodsInfoService;
    private final AnchorSellTaskMapper anchorSellTaskMapper;
    private final ShopSellTaskService shopSellTaskService;
    private final AnchorLivesSessionService livesSessionService;
    private final AnchorLivesRoomService livesRoomService;

    @Override
    public Page<SysSellLivesAnchorPageVO> pageBySys(SysSellLivesAnchorPageDTO queryDTO) {
        //输入店铺名
        Page<SysSellLivesAnchorPageVO> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        page = baseMapper.pageBySys(page, queryDTO);
        page.getRecords().forEach(e -> {
            List<Long> list = taskProductService.listGoodsInfoIdBySellTaskId(e.getShopSellTaskId());
            List<SellLivesChild> sellLivesChildren = BeanUtil.copyToList(goodsInfoService.list(Wrappers.<ShopGoodsInfo>lambdaQuery().in(!CollectionUtils.isEmpty(list), ShopGoodsInfo::getId, list).orderByDesc(ShopGoodsInfo::getCreateTime)), SellLivesChild.class);
            e.setGoodsChildList(sellLivesChildren);
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer pass(Long id) {
        log.info("后台管理通过审核主播直播申请,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), id);
        AnchorSellLivesApply sellLivesApply = checkAudit(id);
        //判断审核时间
        if (sellLivesApply.getStartLivesTime().isBefore(LocalDate.now())) {
            sellLivesApply.setPassFlag(CommonPassFlag.审核未通过.getStatus());
            updateById(sellLivesApply);
            return 1;
        }
        sellLivesApply.setPassFlag(CommonPassFlag.审核通过.getStatus());
        updateById(sellLivesApply);

        //更新主播接取带货任务表状态
        AnchorSellTask anchorSellTask = new AnchorSellTask();
        anchorSellTask.setId(sellLivesApply.getAnchorSellTaskId());
        anchorSellTask.setStatus(AnchorSellTaskStatus.待开播.getStatus());
        anchorSellTaskMapper.updateById(anchorSellTask);

        //创建直播场次
        AnchorLivesRoom room = livesRoomService.getOne(Wrappers.<AnchorLivesRoom>lambdaQuery().eq(AnchorLivesRoom::getAnchorId, sellLivesApply.getAnchorId()));
        if(room == null){
            room = livesRoomService.initLivesRoom(sellLivesApply.getAnchorId());
        }
        AnchorLivesSession livesSession = new AnchorLivesSession();
        livesSession.setLivesRoomId(room.getId());
        livesSession.setLivesSessionName(this.getTaskName(sellLivesApply.getAnchorSellTaskId()));
        livesSession.setAnchorId(room.getAnchorId());
        livesSession.setAnchorName(room.getAnchorName());
        livesSession.setLivesStatus((byte) 1);
        livesSession.setAnchorSellTaskId(sellLivesApply.getAnchorSellTaskId());
        livesSession.setLivesSessionName(sellLivesApply.getLivesSessionName());
        livesSession.setUpdateTime(LocalDateTime.now());
        livesSession.setUpdateBy(SecurityUtils.getUsername());
        livesSessionService.save(livesSession);
        return 0;
    }

    private String getTaskName(Long anchorSellTaskId) {
        String taskName = null;
        AnchorSellTask sellTask = anchorSellTaskMapper.selectById(anchorSellTaskId);
        if(sellTask != null && sellTask.getShopSellTaskId() != null){
            ShopSellTask shopSellTask = shopSellTaskService.getById(sellTask.getShopSellTaskId());
            if(shopSellTask != null){
                taskName = shopSellTask.getTaskName();
            }
        }
        return taskName;
    }

    @Override
    public void noPass(Long id) {
        log.info("后台管理未通过审核带货任务,操作人：{}，操作信息：{}", SecurityUtils.getUsername(), id);
        AnchorSellLivesApply sellLivesApply = checkAudit(id);
        sellLivesApply.setPassFlag(CommonPassFlag.审核未通过.getStatus());
        updateById(sellLivesApply);

        //更新主播接取带货任务表状态
        AnchorSellTask anchorSellTask = new AnchorSellTask();
        anchorSellTask.setId(sellLivesApply.getAnchorSellTaskId());
        anchorSellTask.setStatus(AnchorSellTaskStatus.未通过.getStatus());
        anchorSellTaskMapper.updateById(anchorSellTask);
    }


    @Override
    public SysSellLivesAnchorPageVO sysDetail(Long id) {
        SysSellLivesAnchorPageVO vo = new SysSellLivesAnchorPageVO();

        AnchorSellLivesApply sellLivesApply = baseMapper.selectById(id);
        BeanUtil.copyProperties(sellLivesApply, vo);

        if (null == sellLivesApply) {
            throw new QysException("请检查ID");
        }
        AnchorSellTask anchorSellTask = anchorSellTaskMapper.selectById(sellLivesApply.getAnchorSellTaskId());
        BeanUtil.copyProperties(anchorSellTask, vo);
        ShopSellTask shopSellTask=shopSellTaskService.getById(anchorSellTask.getShopSellTaskId());
        if (null!=shopSellTask){
            vo.setTaskName(shopSellTask.getTaskName());
        }
        List<Long> list = taskProductService.listGoodsInfoIdBySellTaskId(anchorSellTask.getShopSellTaskId());
        if (CollectionUtils.isNotEmpty(list)){
            List<ShopGoodsInfo> shopGoodsInfos=goodsInfoService.list(Wrappers.<ShopGoodsInfo>lambdaQuery().in(ShopGoodsInfo::getId, list));
            List<SellLivesChild> sellLivesChildren = BeanUtil.copyToList(shopGoodsInfos, SellLivesChild.class);
            vo.setGoodsChildList(sellLivesChildren);
        }
        return vo;
    }


    private AnchorSellLivesApply checkAudit(Long id) {
        AnchorSellLivesApply sellLivesApply = baseMapper.selectById(id);
        if (null == sellLivesApply) {
            throw new QysException("请检查ID");
        }
        CommonPassFlag.checkStatus(sellLivesApply.getPassFlag(),CommonPassFlag.审核中);
        return sellLivesApply;
    }


    @Override
    public AnchorSellLivesApply checkRepeat(Long anchorSellTaskId, Long anchorId) {
        return baseMapper.selectOne(Wrappers.<AnchorSellLivesApply>lambdaQuery()
                .eq(AnchorSellLivesApply::getAnchorSellTaskId, anchorSellTaskId)
                .eq(AnchorSellLivesApply::getAnchorId, anchorId).last("limit 1")
        );
    }
}
